package org.jeecg.modules.hc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.RandomUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.hc.entity.HcAliRefund;
import org.jeecg.modules.hc.mapper.HcAliRefundMapper;
import org.jeecg.modules.hc.service.IHcAliRefundService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 支付宝退款
 * @Author: jeecg-boot
 * @Date: 2023-01-12
 * @Version: V1.0
 */
@Service
@Slf4j
public class HcAliRefundServiceImpl extends ServiceImpl<HcAliRefundMapper, HcAliRefund> implements IHcAliRefundService {

    private final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDM5UmfMBFScnOCltaRbXeALSJ1iOomb3baHeXbrElqvOn76ZvjrHma/+ULXDVmKkK+V7rygPcjEKZdawycgtUb8CMUACvpaQrmn3JrIRcrD8GpivPPI23bSRacisXgidyiKU4WkXc8bJg34bZX1gi2ateTFGu1txDX8R3mc+NEPZvdN8NBei0BMEZrP5WjOWsBvlazCGAKzbNdGtsVxND+fjd4/czBBuAXAFwVSJCG3QFvQoYxj7jq30F4Frve8hiu+TzERvba6e096Wg5ea+Y8TMLnMgM5/0wXHHPmfVMUBx2v9qOx4Sj4LP2gC/EBSgHfUoj2OJ/dBCOOHWXcpcdAgMBAAECggEBAMX24uMDNjlKi4Ao7Lcl5Mfa0+hrmI/6MgMbz/Imy+htDkVuuEeJZRT1GP+Y358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D/0/embS5RdxfpSrLv6ehlb8DZ0RlJIJedTXsCTFgf2+6jmP5voRmo/kNSetAl+iHlC8zit";
    private final String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzOVJnzARUnJzgpbWkW13gC0idYjqJm922h3l26xJarzp++mb46x5mv/lC1w1ZipCvle68oD3IxCmXWsMnILVG/AjFAAr6WkK5p9yayEXKw/BqYrzzyNt20kWnIrF4IncoilOFpF3PGyYN+G2V9YItmrXkxRrtbcQ1/Ed5nPjRD2b3TfDQXotATBGaz+VozlrAb5WswhgCs2zXRrbFcTQ/n43eP3MwQbgFwBcFUiQht0Bb0KGMY+46t9BeBa73vIYrvk8xEb22untPeloOXmvmPEzC5zIDOf9MFxxz5n1TFAcdr/ajseEo+Cz9oAvxAUoB31KI9jif3QQjjh1l3KXHQIDAQAB";
    private final String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmbJVDHeWdXPVJHSvna9CG4i2xWK/qbEtb9LB8NXSPw1lKlizJRJMMZWrrIoOXNQnVpzmh9QOlEkYjBGQtyhzFlAB1Myn0wy6F3ONQisNho4M7ahhpwFrJ913Zr3ir+eK9Jd1Cg1uruaejQzOTbvTGNIXdSDSHEHSrq72UjBP2kWYXIaiwVXTCMirfg+cxSA3/SJ6TdkG0k9Oc1aLLo3PUfk49ebQuWxKdRqAOr2pZkBpzFxBfkTnk6pcfE30qg+ReusaEIVbdzIUODkDHPQDeSoQmZlB1xa4240nxwGwtzN7//k4Ag3Bz5meHDMDksKlmpwTSUCz9sWTAdKJWYQEbQIDAQAB";
    private final String appId = "2021003163678411";
    private final String appIdNew = "2021004126684141";


    public HcAliRefund refund(String outTradeNo, String userId, BigDecimal refund) throws AlipayApiException {
        String out_request_no = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtils.getRandomStr();

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "GBK", alipayPublicKey, "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("refund_amount", refund);
        bizContent.put("out_request_no", out_request_no);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);

        log.info(response.getBody());

        HcAliRefund aliRefund = new HcAliRefund().setUserId(userId).setOutTradeNo(outTradeNo)
                .setOutRequestNo(out_request_no).setRefundAmount(refund);

        if (response.isSuccess()) {
            aliRefund.setRefundFee(new BigDecimal(response.getRefundFee()));
        } else {
            log.error(response.getMsg());
            throw new JeecgBootException("调用失败");
        }

        this.save(aliRefund);
        return aliRefund;
    }

    public HcAliRefund queryRefund(String refundId) throws AlipayApiException {
        HcAliRefund hcAliRefund = this.getById(refundId);

        if (hcAliRefund == null) {
            throw new JeecgBootException("订单号不存在");
        }

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "GBK", alipayPublicKey, "RSA2");
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", hcAliRefund.getOutTradeNo());
        bizContent.put("out_request_no", hcAliRefund.getOutRequestNo());

        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);

        if (response.isSuccess()) {
            HcAliRefund update = new HcAliRefund().setId(hcAliRefund.getId())
                    .setTotalAmount(new BigDecimal(response.getTotalAmount())).setRefundStatus(response.getRefundStatus());
            this.updateById(update);
            return update;
        } else {
            log.error(response.getMsg());
            throw new JeecgBootException("调用失败");
        }
    }
}
